const express = require('express');
const { findById } = require('../models/Home');
const Home = require("../models/Home");
const router = express.Router();
const Book = require("../models/Book");
//新建顶级
router.post("/new", (req, res) => {
    let newHome = new Home({
        homename: req.body.homename,
        isclass:req.body.isclass,
        sort: req.body.sort,
    })
    newHome.save()
        .then(home => res.json({ data: home, status: 200 }))
        .catch(err => console.log(err));
})

//新建顶级子分类
router.post("/add/:id", (req, res) => {
    const homedate = {};
    if (req.body.bookid) { homedate.bookid = req.body.bookid };
    if (req.body.bookname) { homedate.bookname = req.body.bookname };
    
    Home.findOneAndUpdate(
        { _id: req.params.id },
        { $addToSet: { pic: homedate } },
        { new: true }
    ).then(home => res.json({
        data: home,
        status: 200
    }))
         .catch(err => console.log(err))

})

//获取顶级全部
router.post("/getTop", (req, res) => {
    let a = req.body.pageSize;
    let b = req.body.currentPage
    let c = (b - 1) * a;
    //console.log(req.body.sort );
    Home.find({ sort: req.body.sort }).skip(c).limit(a)
        .then(h => {
            Home.find({ sort: req.body.sort }).countDocuments(true)
                .then(num => res.send({data:h,num:num,status:200}))
        })   
})
//更新顶级状态
router.post("/updateTopState/:id", (req, res) => {
    Home.findByIdAndUpdate(req.params.id, { $set: { state: req.body.state } })
        .then(res.sendStatus(200))
})
//获取顶级子分类
router.post("/getChild", (req, res) => {
    let a = req.body.pageSize;
    let b = req.body.currentPage
    let c = (b - 1) * a;
    Home.find({ sort: req.body.sort, isclass: req.body.isclass }).skip(c).limit(a)
        .then(h => {
            Home.find({ sort: req.body.sort, isclass: req.body.isclass }).countDocuments(true)
                .then(num => res.send({ data: h, num: num, status: 200 }))
        })
})
//更新顶级子分类
router.post("/updata", (req, res) => {
    if (req.body.bookid) { bookid = req.body.bookid }
    if (req.body.bookname) {bookname = req.body.bookname }
    Home.findOneAndUpdate({ "pic._id": req.body.id }, { $set: { 'pic.$.bookname': bookname, 'pic.$.bookid': bookid }},{ new: true })
        .then(a =>
            res.json(a))
})
//更新子分类图片
router.post("/updataPic", (req, res) => {
    //console.log(req.body);
    // if (req.body.picUrl) { bookdata.pic.$.picUrl = req.body.picUrl }
    Home.findOneAndUpdate({ "pic._id": req.body.id }, { $set: { 'pic.$.picUrl': req.body.picUrl } }, { new: true })
        .then(a =>
            res.json(a))
    // { 'pic.$.bookname': bookname, 'pic.$.bookid': bookid, 'pic.$.picUrl': picUrl}
})
//删除图片
router.post("/removePic", (req, res) => {
    Home.findOneAndUpdate({ "pic._id": req.body.id }, { $pull: { pic: { _id: req.body.id } } }, { new: true })
        .then(a => res.json(a))
})
//获取主页轮播图
router.get("/homeLunBo", (req, res) => {
    Home.findOne({ sort: "首页推荐", isclass: "轮播图", state: 1 }, { pic: 1 })
        .then(h => res.send({data:h,status:200}))
})
//搜藏榜
router.get("/shouList", (req, res) => {
    Book.find({ state: 0 }, { avatar: 1, bookname: 1, thiscollection:1 }).sort({ "thiscollection": -1 }).limit(10)
        .then(books =>
            res.send({ data: books,status: 200 })
        )
})
//字数榜
router.get("/sizeList", (req, res) => {
    Book.find({ state: 0 }, { avatar: 1, bookname: 1, size:1}).sort({ "size": -1 }).limit(10)
        .then(books =>
            res.send({ data: books,status: 200 })
        )
})

//根据分类获取推荐   ----新书首发
router.post("/classTuiNew", (req, res) => {
    let thisClass = `${req.body.isclass}推荐`
    Home.findOne({ sort: thisClass, state: 1, isclass: '新书首发' })
        .then(home => {
            let idArr = [];
            let p = new Promise((res, rej) => {
                for (let i = 0; i < home.pic.length; i++){
                    let { a, bookid, c } = home.pic[i]
                    idArr.push(bookid)
                }
            })
            p.then(
                Book.find({ _id: { $in: idArr }, state: 0 }, { bookname: 1, writername: 1, writerid: 1,isend:1 })
                    .then(book => res.send({data:book,isclass:home.isclass,status:200}))
            )
            }
        )
})

//根据分类获取推荐   ----编辑推荐
router.post("/classTuiEditor", (req, res) => {
    let thisClass = `${req.body.isclass}推荐`
    Home.findOne({ sort: thisClass, state: 1, isclass: '编辑推荐' })
        .then(home => {
            let idArr = [];
            let p = new Promise((res, rej) => {
                for (let i = 0; i < home.pic.length; i++) {
                    let { a, bookid, c } = home.pic[i]
                    idArr.push(bookid)
                }
            })
            p.then(
                Book.find({ _id: { $in: idArr }, state: 0 }, { bookname: 1, writername: 1, writerid: 1, isend: 1 })
                    .then(book => res.send({ data: book, isclass: home.isclass, status: 200 }))
            )
        }
        )
})

//根据分类获取推荐   ----完结精品
router.post("/classTuiEnd", (req, res) => {
    let thisClass = `${req.body.isclass}推荐`
    Home.findOne({ sort: thisClass, state: 1, isclass: '完结精品' })
        .then(home => {
            let idArr = [];
            let p = new Promise((res, rej) => {
                for (let i = 0; i < home.pic.length; i++) {
                    let { a, bookid, c } = home.pic[i]
                    idArr.push(bookid)
                }
            })
            p.then(
                Book.find({ _id: { $in: idArr }, state: 0 }, { bookname: 1, writername: 1, writerid: 1, isend: 1})
                    .then(book => res.send({ data: book, isclass: home.isclass, status: 200 }))
            )
        }
        )
})

//根据分类获取推荐   ----热门连载
router.post("/classTuiHot", (req, res) => {
    let thisClass = `${req.body.isclass}推荐`
    Home.findOne({ sort: thisClass, state: 1, isclass: '热门连载' })
        .then(home => {
            let idArr = [];
            let p = new Promise((res, rej) => {
                for (let i = 0; i < home.pic.length; i++) {
                    let { a, bookid, c } = home.pic[i]
                    idArr.push(bookid)
                }
            })
            p.then(
                Book.find({ _id: { $in: idArr }, state: 0 }, { bookname: 1, writername: 1, writerid: 1, isend: 1 })
                    .then(book => res.send({ data: book, isclass: home.isclass, status: 200 }))
            )
        }
        )
})


//删除一个推荐
router.delete("/deleteThisTui/:id", (req, res) => {
    Home.findByIdAndDelete(req.params.id)
        .then(res.sendStatus(200))
})
//修改一个推荐的名称
router.post("/updataThisTui/:id", (req, res) => {
    Home.findByIdAndUpdate(req.params.id, { $set: { homename: req.body.name } })
        .then(res.sendStatus(200)
            )
})


module.exports = router;